package com.freewater.springboot.demo.ioc.beanpostprocessor.instantiationaware;

import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;


/**
 * 自定义处理器
 *
 * @author dengp
 */
public class MyInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {

    /**
     * BeanPostProcessor接口中的方法
     * 在Bean的自定义初始化方法之前执行
     * Bean对象已经存在了
     */
    @Override
    public Object postProcessBeforeInitialization(@NotNull Object bean, @NotNull String beanName) throws BeansException {
        // TODO Auto-generated method stub
        System.out.println(">>postProcessBeforeInitialization");
        return bean;
    }

    /**
     * BeanPostProcessor接口中的方法
     * 在Bean的自定义初始化方法执行完成之后执行
     * Bean对象已经存在了
     */
    @Override
    public Object postProcessAfterInitialization(@NotNull Object bean, @NotNull String beanName) throws BeansException {
        System.out.println("<<postProcessAfterInitialization");
        return bean;
    }

    /**
     * InstantiationAwareBeanPostProcessor中自定义的方法
     * 在方法实例化之前执行
     * Bean对象还没有
     */
    @Override
    public Object postProcessBeforeInstantiation(@NotNull Class<?> beanClass, @NotNull String beanName) throws BeansException {
        System.out.println("--->postProcessBeforeInstantiation");
        // User放回了自定义的代理对象，后续的Populate阶段不再执行，直接执行BeanPostProcessor的postProcessAfterInitialization方法
        /*if (User.class.equals(beanClass)) {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(beanClass);
            enhancer.setCallback((MethodInterceptor) (o, method, objects, methodProxy) -> {
                System.out.println("目标方法前:" + method + "\n");
                Object object = methodProxy.invokeSuper(o, objects);
                System.out.println("目标方法后:" + method + "\n");
                return object;
            });
            User user = (User) enhancer.create();
            System.out.println("--->return proxy user object");
            return user;
        }*/
        return null;
    }

    /**
     * InstantiationAwareBeanPostProcessor中自定义的方法
     * 在方法实例化之后执行
     * Bean对象已经创建出来了
     */
    @Override
    public boolean postProcessAfterInstantiation(@NotNull Object bean, @NotNull String beanName) throws BeansException {
        System.out.println("<---postProcessAfterInstantiation");
        return true;
    }

    /**
     * InstantiationAwareBeanPostProcessor中自定义的方法
     * 可以用来修改Bean中属性的内容
     */
    @Override
    public PropertyValues postProcessProperties(@NotNull PropertyValues pvs, @NotNull Object bean,
                                                @NotNull String beanName) throws BeansException {
        System.out.println("<---postProcessPropertyValues--->");
        return pvs;
    }
}